$(function () {
    // const DEV_URL = "http://localhost:9999";
    // const DEV_URL = "https://publishdemo.mpen.com.cn";
/*uselocal2pack*/
    const USE_LOCAL = true;
    /*
uselocal2pack/*
    const USE_LOCAL = false;
    /**/
    
    const DEV_URL = USE_LOCAL ? "http://test/" : "http://localhost:9999";
    let page = 0; //当前页码
    let size = 1;
    let readLength = ''; //存储当前点读div的数量
    let imageWidth = $(window).width() / 2; //可见区域宽度
    let imageHeight = $(window).height() / 2; //可见区域高度
    let windowWidth = $(window).width();//浏览器的宽度
    let windowHeight = $(window).height();//浏览器的高度
    let pageX = 0; //左侧的留白
    let pageY = 0; //右侧的留白
    let audioUrl = ''; //音频地址
    let videoUrl = ''; //视频地址
    let position = 'left';//控制面板的显示位置
    let imgLen = '';//图片总数
    let smlPage = '';//
    let rangeLen = '';
    let zoom = 1;//当前缩放系数
    let lastZoom = 1;//上一次缩放系数
    let imgW1;//第一个图片的当前宽度
    let imgW2;//第二个图片的当前宽度
    let imgW;//可见图片的总宽度
    let imgH;//可见图片的高度
    let mouseMovePosition = true;//移动页面的时候判断移动距离是否大于10的时候可以移动否则是点读
    let turnPageSave={};//绘制存储
    let insertPosition = [];//记录外部插入word等的position以及width，height
    let onSize=false;//判断是否是浏览器窗口发生变化触发的insert函数
    let res;//存储外部图片返回来的数据
    $(".main").loading();
    $.ajax({
        type: "GET",
        contentType: "application/json",
        // url: DEV_URL + "/v1/books/ebookInfo?action=getEBookPhoto&bookId=ff80808156ca3d900156cb19feff004c&ratio=low&insideKey=INTERNAL_VALIDATION_KEY",
        url: DEV_URL + (USE_LOCAL ? 'listpageimg' : '/v1/books/ebookInfo?action=getEBookPhoto&bookId=ff80808156ca3d900156cb19feff004c&ratio=low&insideKey=INTERNAL_VALIDATION_KEY'),
        success: async (res) => {
            let data = res.data;
            // data.push('http://cdn.mpen.com.cn/incoming/course/temp/decodeMpp/ff80808156ca3d900156cacf93420013/1579071735//low/0001_九年级下_封面.jpg?auth_key=1632292822-0-0-cc828f971c0c5174e139232ba7e93481');
            let domImage = '';
            let smlImage = '';
            let insertDom = '';//图标
            imgLen = data.length;
            $('#img_range').attr('max', data.length).attr('value', size);
            rangeLen = (canvas.width - 790) / imgLen;
            $('#img_range_con').css('width', rangeLen * (size - 1) + 'px');

            for (let i = 0; i < data.length; i += 2) {
                if (data[i + 1] == undefined) {
                    domImage += `<div style='transform-origin: 0 0;'><img src='' data-src='${data[i]}' page-num='${i + 1}' div-chil='1'/><div style="width: 33.33%;"><div></div>`;

                } else {
                    domImage += `<div style='transform-origin: 0 0;'><img onclick="" src='' data-src='${data[i]}' page-num='${i + 1}' div-chil='1'/><img src='' data-src='${data[i + 1]}' page-num='${i + 2}' div-chil='2'/></div>`;
                }
                insertDom += `<div></div>`;
            }
            for (let i = 0; i < data.length; i++) {
                smlImage += `<div style='width:100%;height:100%'><img  src='' data-src='${data[i]}' page-num='${i + 1}' style='width:100%;height:100%'/></div>`;
            }

            $('.click-read-all').html(domImage);
            $('.insert-img').html(insertDom);
            readLength = $('.click-read-all>div').length;

            for(let i=0;i<readLength;i++){
                turnPageSave[i]=[]
            }
            $('.click-read-all>div').css({ display: 'none' });
            $('.insert-img>div').css({ display: 'none' });
            $('.click-read-all>div').eq(0).css({ display: 'flex' });
            $('.insert-img>div').eq(0).css({ display: 'block' });
            onSize=false;
            insert(0);
            $('.sml-img').html(smlImage);
            $(".main").loadingClose();
        }
    });

    // 图片进度条
    $('.bar').click(function () {
        $('.select-brush').hide();
        $('.select-eraser').hide();
        $('.img-range-wrap-pagin').show();
        $('#img_range_con').css('width', rangeLen * (Number($('#img_range').val()) - 1) + 'px');
        $('.bar').hide();
        $('.sml-img').hide();
    })
    // 右侧点击
    $('.tools-btn-right').click(function () {
        $('.tools').show();
        $('.tools').css({ 'right': '10px', 'left': 'auto' });
        $('.tools-btn-right').hide();
        $('.tools-btn-left').show();
        // $('.bar').show();
        $('.img-range-wrap-pagin').hide();
        position = 'right';
        // $('.select-brush').css({'right':'192px','left':'auto'});
        $('.select-brush').hide();
    });
    // 左侧点击
    $('.tools-btn-left').click(function () {
        $('.tools').show();
        $('.tools').css({ 'left': '10px', 'right': 'auto' });
        $('.tools-btn-right').show();
        $('.tools-btn-left').hide();
        // $('.bar').show();
        position = 'left';
        $('.select-brush').hide()
        $('.img-range-wrap-pagin').hide();
    })
    // 图片进度条
    $('#img_range').on('input', function (e) {
        size = Number(this.value);
        if (size % 2 != 0) {
            page = parseInt(size / 2) + 1;
        } else {
            page = parseInt(size / 2);
        }
        page = page - 1;
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=false;
        insert(page);
        $('#img_range_con').css('width', rangeLen * (size - 1) + 'px');
        change();
        stopAudio();
        // ctxClear(ctx);
    })
    // 翻页跳转
    $('#go_to_page').click(function () {
        if (Number($('#pagination').val()) <= 1) {
            size = 1;
        } else if (Number($('#pagination').val()) >= imgLen) {
            size = imgLen;
        } else {
            size = Number($('#pagination').val());
        }

        if (size % 2 != 0) {
            page = parseInt(size / 2) + 1;
        } else {
            page = parseInt(size / 2);
        }
        page = page - 1;
        $('#img_range_con').css('width', rangeLen * (size - 1) + 'px');
        $('#img_range').attr({ value: size });
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=false;
        insert(page);
        change();
        stopAudio();
        // ctxClear(ctx);
    })
    // 进度条鼠标悬停
    $('#img_range').mouseover(function (e) {
        e.preventDefault();
        let rangeX = e.clientX - 276;
        let num = (canvas.width - 552 - 238) / imgLen;
        smlPage = Math.ceil(rangeX / num) - 1;
        smlImageLoad($('.sml-img>div').eq(smlPage));
        $('.sml-img').show();
        $('.sml-img>div').css({ display: 'none' });
        $('.sml-img>div').eq(smlPage).css('display', 'block');

        $('.sml-img').css('left', rangeX + 'px');
    })
    $('.img-range-wrap').mousemove(function (e) {
        // e.stopPropagation();
        $('.sml-img').show();
        let rangeX;
        if (e.clientX <= 276) {
            rangeX = 1;
        } else if (e.clientX > canvas.width - 276 - 238) {
            rangeX = canvas.width - 276 - 238 - 276;

        } else {
            rangeX = e.clientX - 276;
        }
        let num = (canvas.width - 552 - 238) / imgLen;
        smlPage = Math.ceil(rangeX / num) - 1;
        smlImageLoad($('.sml-img>div').eq(smlPage));
        $('.sml-img>div').css({ display: 'none' });
        $('.sml-img>div').eq(smlPage).css('display', 'block');
        if (e.clientX > canvas.width - 276 - 238) {
            $('.sml-img').css('left', (canvas.width - 276 - 238 - 276 - 98) + 'px');
        } else if (e.clientX < 276) {
            $('.sml-img').css('left', '-98' + 'px');
        } else {
            $('.sml-img').css('left', (rangeX - 98) + 'px');
        }

    })
    $('.img-range-wrap').mouseup(function (e) {
        if (smlPage % 2 != 0) {
            page = parseInt(smlPage / 2) + 1;
        } else {
            page = parseInt(smlPage / 2);
        }
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=false;
        insert(page);
        $('#img_range').attr('value', page * 2);
        change();
        stopAudio();
        // ctxClear(ctx);

    })
    $('.img-range-wrap').on('touchstart', function (e) {
        e.stopPropagation();
        let rangeX = e.touches[0].clientX - 276;
        let num = (canvas.width - 552 - 238) / imgLen;
        let val = Math.ceil(rangeX / num) - 1;
        smlImageLoad($('.sml-img>div').eq(val));
        $('.sml-img').show();
        $('.sml-img>div').css({ display: 'none' });
        $('.sml-img>div').eq(val).css('display', 'block');
        if (e.clientX > canvas.width - 276) {
            $('.sml-img').css('left', rangeX - 238 + 'px');
        } else if (e.clientX < 276) {
            $('.sml-img').css('left', 276 + 'px');
        } else {
            $('.sml-img').css('left', (rangeX - 98) + 'px');
        }
        $('.select-brush').hide();
        $('select-eraser').hide();
    })
    $('.img-range-wrap').on('click', function (e) {
        $('.sml-img').hide();
    })
    $('.img-range-wrap').on('touchmove', function (e) {
        e.stopPropagation();

        let rangeX;
        if (e.touches[0].clientX <= 276) {
            rangeX = 1;
        } else if (e.touches[0].clientX > canvas.width - 276 - 238) {
            rangeX = canvas.width - 276 - 238 - 276;

        } else {
            rangeX = e.touches[0].clientX - 276;
        }
        let num = (canvas.width - 552 - 238) / imgLen;
        smlPage = Math.ceil(rangeX / num) - 1;

        smlImageLoad($('.sml-img>div').eq(smlPage));
        $('.sml-img').show();
        $('.sml-img>div').css({ display: 'none' });
        $('.sml-img>div').eq(val).css('display', 'block');
        if (e.touches[0].clientX > canvas.width - 276 - 238) {
            $('.sml-img').css('left', (canvas.width - 276 - 238 - 276 - 98) + 'px');
        } else if (e.touches[0].clientX < 276) {
            $('.sml-img').css('left', '-98' + 'px');
        } else {
            $('.sml-img').css('left', (rangeX - 98) + 'px');
        }
    })
    $('#range').on('touchmove', function (e) {
        e.stopPropagation();
    })
    $('#img_range').on('touchmove', function (e) {
        e.stopPropagation();
        let rangeX;
        if (e.touches[0].clientX <= 276) {
            rangeX = 1;
        } else if (e.touches[0].clientX > canvas.width - 276 - 238) {
            rangeX = canvas.width - 276 - 238 - 276;

        } else {
            rangeX = e.touches[0].clientX - 276;
        }
        let num = (canvas.width - 552 - 238) / imgLen;
        let val = Math.ceil(rangeX / num) - 1;
        smlImageLoad($('.sml-img>div').eq(val));
        $('.sml-img').show();
        $('.sml-img>div').css({ display: 'none' });
        $('.sml-img>div').eq(val).css('display', 'block');
        if (e.touches[0].clientX > canvas.width - 276 - 238) {
            $('.sml-img').css('left', (canvas.width - 276 - 238 - 276 - 98) + 'px');
        } else if (e.touches[0].clientX < 276) {
            $('.sml-img').css('left', '-98' + 'px');
        } else {
            $('.sml-img').css('left', (rangeX - 98) + 'px');
        }
    })
    $('.img-range-wrap').mouseleave(function (e) {
        $('.sml-img').hide();
    })
    $('.img-range-wrap-pagin').mouseleave(function (e) {

        $('.bar').show();
        $('.sml-img').hide();
        $('.img-range-wrap-pagin').hide();
    })
    $('.img-range-wrap').on('touchend', function (e) {
        $('.sml-img').hide();

    })

    $('#brush').click(function () {
        if (position == 'right') {
            $('.select-brush').css({ 'right': '192px', 'left': 'auto' });
        } else {
            $('.select-brush').css({ 'left': '192px', 'right': 'auto' });
        }
    })
    $('#eraser').click(function () {
        if (position == 'right') {
            $('.select-eraser').css({ 'right': '192px', 'left': 'auto' });
        } else {
            $('.select-eraser').css({ 'left': '192px', 'right': 'auto' });
        }
    })

    //播放器限时处理
    if (USE_LOCAL) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', DEV_URL + 'checktimelis', true);
        xhr.onload = function(e){
            var res = JSON.parse(e.srcElement.responseText)
            if(!res.isInLisTime){
                $(".end-time").show();
            }
        };
        xhr.send(null);
        
    }

    //当浏览器大小变化时
    $(window).resize(function () {
        imageWidth = $(window).width() / 2;
        imageHeight = $(window).height() / 2;
        windowWidth = $(window).width();
        windowHeight = $(window).height();
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=true;
        insert(page);
        rangeLen = (canvas.width - 790) / imgLen;
        $('#img_range_con').css('width', rangeLen * (size - 1) + 'px');
    });
    //图片懒加载
    async function imageLoad(div) {
        return new Promise((resolve) => {
            div.children('img').each(function (index, item) {
                if ($(item).attr('src') === "") {
                let src = $(item).attr('data-src');
                $(item).attr('src', src);
                }
                //设置图片高度
                var img = new Image();
                img.src = $(item).attr('src');
                img.onload = function () {
                    let height = (img.height * imageWidth * 2 / 3) / img.width;
                   
                    $(item).css({ 'height': windowHeight });
                    width=$(item).width();
                    if(div.children('div')){
                        div.children('div').each(function (index, divItem) {
                            
                            $(divItem).css({ 'height': windowHeight,'width':width });
                        })
                    }
                    resolve([$(item).width(), $(item).height()]);
                }
            })
           
        })
    };
    // 进度条图片懒加载
    function smlImageLoad(div) {
        div.children('img').each(function (index, item) {
            if ($(item).attr('src') === "") {
            let src = $(item).attr('data-src');
            $(item).attr('src', src);
            }
            //设置图片高度
            var img = new Image();
            img.src = $(item).attr('src');
        })
    }
    
    //获取视频地址
    function getVideoUrl(path) {
        if (path && path.endsWith('meta.json')) {
            let url = 'https://stream-1-aliyuncdn.webtrn.cn/' + path;
            $.ajax({
                type: 'GET',
                contentType: "application/json",
                url: url,
                success: function (res) {
                    let mp4 = res.mp4;
                    videoUrl = url.replace("meta.json", mp4);
                    $('.audio').attr('src', '');
                    $('#example_video').attr('src', videoUrl);

                    $('.video-play').css({ display: 'block' });
                }
            })
        }
    };
    //关闭视频
    $('#hide_video').click(function () {
        $('.video-play').css({ display: 'none' });
        $('#example_video').attr('src', '');
        $('.red-dot').css({ display: 'none' });
    });
    // 关闭外部插入图片显示
    $('#hide_img').click(function () {
        $('.external-img').css({ display: 'none' });
        $('#example_img').attr('src', '');

    })
    //修改小红点
    function showDot(x, y) {
        $('.red-dot').css({
            left: x - 5 + pageX + 'px',
            top: y - 5 + pageY + 'px'
        });
    };
    //音频播放结束
    $('.audio').on('ended', function () {
        stopAudio();
    });
    //停止播放音频，清空数据和小红点
    function stopAudio() {
        $('.audio').attr('src', '');
        $('.red-dot').css({ display: 'none' });
    };
    // 上一页
    $("#left").click(function () {
        save(page,url);
        page--;
        if (page <= 0) {
            page = 0;
        }
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=false;
        insert(page);
        $('.img-range-wrap-pagin').hide();
        $('.select-brush').hide();
        $('.select-eraser').hide();
        // $('.bar').show();
        $('#img_range').attr('value', page * 2);
        change();
        stopAudio();
        
        if(turnPageSave[page].length==0){
            url=new ImageData(data, 2, 2);
            ctx.putImageData(url, 0, 0);
           }else{
            ctx.putImageData(turnPageSave[page][turnPageSave[page].length-1], 0, 0);
            url=turnPageSave[page][turnPageSave[page].length-1];
            console.log(url);
           }
           
        // ctxClear(ctx);
    });
    
// 翻页存储绘制路径
function save(page,url){
    turnPageSave[page]=[]
    turnPageSave[page].push(url);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // ctx.putImageData(turnPageSave[page][0], 0, 0);
}
    //下一页
    $("#right").click(function () {
        save(page,url);
        page++;
        if (page >= readLength) {
            // page = 0;
            page = readLength - 1;
        }
        $('.select-brush').hide();
        $('.select-eraser').hide();
        // imageLoad($('.click-read-all>div').eq(page));
        onSize=false;
        insert(page);
        $('.img-range-wrap-pagin').hide();
        // $('.bar').show();
        $('#img_range').attr('value', page * 2);
        change();
        stopAudio();
       if(turnPageSave[page].length==0){
        url=new ImageData(data, 2, 2);
        ctx.putImageData(url, 0, 0);
       }else{
        ctx.putImageData(turnPageSave[page][turnPageSave[page].length-1], 0, 0);
        url=turnPageSave[page][turnPageSave[page].length-1];
       }
        // ctxClear(ctx);
    });
    // 隐藏
    $('#hidden').click(function () {
        $('.tools-btn-left').show();
        $('.tools-btn-right').show();
        // $('.bar').show();
        $('.tools').hide();
        $('.select-brush').hide();
        $('.select-eraser').hide();
        $('.img-range-wrap-pagin').hide();
    })
    // 下课
    $('#close').click(function () {
        // window.location.href = "about:blank"; 
        window.close();
    })
    // 播放器过期关闭
    $('#end_btn').click(function () {
        // window.location.href = "about:blank";
        window.close();
    })
    // 放大画面 最大放大10倍
    $('#enlarge').click(function (e) {
        lastZoom = zoom;
        if (zoom > 4) {
            zoom = 10;
        } else {
            zoom = zoom * 2;
        }

        changeFactor(zoom);
    })
    // 缩小画面 最小缩到1倍
    $('#zone_out').click(function () {
        lastZoom = zoom;
        if (zoom == 10) {
            zoom = 8;
        } else if (zoom < 2) {
            zoom = 1;
        } else {
            zoom = zoom / 2;
        }
        changeFactor(zoom);
    })
    // 还原 还原到一倍
    $('#reduction').click(function () {
        zoom = 1;
        changeFactor(zoom);
    })

    // 放大画面后上下左右拖动屏幕
    mainMove();
    function mainMove() {
        let lastMousePoint = { x: '', y: '' };
        let nowMousePoint = { x: '', y: '' };
        let moveX = 0;
        let moveY = 0;
        let drag = false;//是否可以进行拖动
        let mainLeft;//main元素的left
        let mainTop;//main元素的TOP
        let left;//main元素里面的图片左侧留白
        let top;//main元素里面的图片上侧留白
        let mainW;//main的width
        let mainH;
        // move
        function wMove(x, y, moveX, moveY) {
            if (imgW > windowWidth) {//图片的宽度大于浏览器的宽度可以发生拖拽页面
                if (Math.abs(moveX) > 10 || Math.abs(moveY) > 10) {//移动的X轴距离或者移动的Y轴距离大于10的时候可以进行拖拽页面，否则触发点读事件
                    if (mainLeft + moveX <= -(mainW - windowWidth - (mainW / 2 - imgW2))) {//边缘判断，当main元素左侧距离+鼠标移动距离>=屏幕的宽度-main图片右侧留白
                        $('.main').css({ left: -(mainW - windowWidth - (mainW / 2 - imgW2)) + 'px' });//此时的main元素的left值固定，为main元素的宽度-浏览器的宽度-main里面图片的右侧留白

                    } else if (mainLeft + moveX <= left) {//mian元素的left+鼠标X轴移动的距离>main元素里面图片的留白
                        $('.main').css({ left: mainLeft + moveX + 'px' });//此时main元素的left为本身的main的left+moveX

                    } else {//mian元素的left+鼠标X轴移动的距离<main元素里面图片的留白
                        $('.main').css({ left: left + 'px' });//此时main元素的left就是mian元素里面图片的留白
                    }
                }
            } else {
                moveX = 0;
            }
            if (imgH > windowHeight) {
                if (Math.abs(moveX) > 10 || Math.abs(moveY) > 10) {
                    if (mainTop + moveY <= -(mainH - windowHeight - ((mainH - imgH) / 2))) {
                        $('.main').css({ top: -(mainH - windowHeight - ((mainH - imgH) / 2)) + 'px' });
                    } else if (mainTop + moveY <= top) {
                        $('.main').css({ top: mainTop + moveY + 'px' });
                    } else {
                        $('.main').css({ top: top + 'px' });
                    }
                }
            } else {
                moveY = 0;
            }
        }
        $('.main').mousedown(function (e) {
            if (!isRead) {
                return;
            }
            drag = true;
            mouseMovePosition = true;
            lastMousePoint.x = e.clientX;
            lastMousePoint.y = e.clientY;
            moveX = 0;
            moveY = 0;
            mainLeft = Number(Number($('.main').position().left).toFixed(2));
            mainTop = Number(Number($('.main').position().top).toFixed(2));
            left = Number(Number(-((windowWidth * zoom) / 2 - imgW1)).toFixed(2));
            top = Number(Number(-(windowHeight * zoom - imgH) / 2).toFixed(2));
            mainW = $('.main').width() * zoom;
            mainH = $('.main').height() * zoom;

        })
        $('.main').mousemove(function (e) {
            if (!isRead) {
                return;
            }
            if (drag == true) {
                nowMousePoint.x = e.clientX;
                nowMousePoint.y = e.clientY;
                moveX = e.clientX - lastMousePoint.x;//鼠标移动X轴距离
                moveY = e.clientY - lastMousePoint.y;//鼠标移动Y轴距离
                wMove(nowMousePoint.x, nowMousePoint.y, moveX, moveY);
            }
        })
        $('.main').mouseup(function (e) {
            if (!isRead) {
                return;
            }
            if (Math.abs(moveX) > 10 || Math.abs(moveY) > 10) {//鼠标移动的X或者Y是否大于10来判断触发拖拽页面事件还是点读事件
                mouseMovePosition = false;
            } else {
                mouseMovePosition = true;
            }
            drag = false;
        })

        $('.main').on('mousewheel', function (event) {//滚乱事件缩放页面
            lastZoom = zoom;
            if (event.originalEvent.deltaY > 0) {//上滚
                if (zoom == 10) {
                    zoom = 8;
                } else if (zoom < 2) {
                    zoom = 1;
                } else {
                    zoom = zoom / 2;
                }
            } else if (event.originalEvent.deltaY < 0) {//下滚

                if (zoom > 4) {
                    zoom = 10;
                } else {
                    zoom = zoom * 2;
                }
            }
            changeFactor(zoom);
        })
        $('.main').on('touchstart', function (e) {//触屏事件
            if (!isRead) {
                return;
            }
            drag = true;
            lastMousePoint.x = e.touches[0].clientX;
            lastMousePoint.y = e.touches[0].clientY;
            mainLeft = Number(Number($('.main').position().left).toFixed(2));
            mainTop = Number(Number($('.main').position().top).toFixed(2));
            left = Number(Number(-((windowWidth * zoom) / 2 - imgW1)).toFixed(2));
            top = Number(Number(-(windowHeight * zoom - imgH) / 2).toFixed(2));
            mainW = $('.main').width() * zoom;
            mainH = $('.main').height() * zoom;
        })
        $('.main').on('touchmove', function (e) {
            if (!isRead) {
                return;
            }
            if (drag == true) {
                nowMousePoint.x = e.touches[0].clientX;
                nowMousePoint.y = e.touches[0].clientY;
                moveX = e.touches[0].clientX - lastMousePoint.x;
                moveY = e.touches[0].clientY - lastMousePoint.y;
                wMove(nowMousePoint.x, nowMousePoint.y, moveX, moveY);
            }
        })
        $('.main').on('touchend', function () {
            if (!isRead) {
                return;
            }
            drag = false;
        })
    }

    //点读
    $('.main').click(function (event) {
        $('.red-dot').css({display:'none'})
        if (!isRead || !mouseMovePosition) {
            return;
        }
        let clientX = event.offsetX; //鼠标x轴
        let clientY = event.offsetY; //鼠标y轴
        let childWidth = $('.click-read-all>div').eq(page).children().eq(0).width() * 2;  //当前内容宽度
        let childHeight = $('.click-read-all>div').eq(page).children().eq(0).height();    //当前内容高度
        let viewWidth = windowWidth;  //浏览器宽度
        let viewHeight = windowHeight;  //浏览器高度
        pageX = (viewWidth - childWidth) / 2;  //左侧的留白
        pageY = (viewHeight - childHeight) / 2; //上侧的留白
        if (clientX - pageX <= childWidth &&
            clientY - pageY <= childHeight &&
            clientX - pageX >= 0 &&
            clientY - pageY >= 0
        ) {
            let childX = clientX - pageX;
            let chIldY = clientY - pageY;
            let imageElement = $('.click-read-all>div').eq(page).children();
            let pageNum;
            let x;
            let y;
            if (childX <= childWidth / 2) {
                pageNum = Number(imageElement.eq(0).attr('page-num'));
                x = parseInt((childX * 1000) / imageElement.eq(0).width());
                y = parseInt((chIldY * 1000) / imageElement.eq(0).height());
            } else {
                pageNum = Number(imageElement.eq(1).attr('page-num'));
                x = parseInt(((childX - childWidth / 2) * 1000) / imageElement.eq(1).width());
                y = parseInt((chIldY * 1000) / imageElement.eq(1).height());
            }
            let options = {
                bookInfo: {
                    id: 'ff80808156ca3d900156cb19feff004c'
                },
                code: {
                    type: 'POSITION',
                    mpPoint: {
                        x: x,
                        y: y,
                        pageNum: pageNum
                    }
                }
            };
            showDot(childX, chIldY);
            getVideo(options);
            $('.img-range-wrap-pagin').hide();
            // $('.bar').show();
        }
    });
     function getInsertCon(filename){
         return new Promise((resolve,reject)=>{
            if(!USE_LOCAL){
                resolve('')
            }else{
                let xhrt = new XMLHttpRequest();
                xhrt.open('POST', DEV_URL + 'getUserFileJson', true);
                xhrt.onload=function(e){
                    
                    resolve(e.srcElement.responseText)
                }
                xhrt.send(JSON.stringify({ "filename": filename }));
            }
            
         })
       
    }
    // 获取图片宽度
    function getImageWidth(url,callback){
        let img=new Image();
        img.src=url;
        if(img.complete){
            callback(img.width,img.heigth);
        }else{
            img.onload=function(){
                callback(img.width,img.height)
            }
        }
    }
    //获取音频文件 音频播放
    function getVideo(data) {
        if (USE_LOCAL) {
            let pageNum = data.code.mpPoint.pageNum;
            let x = data.code.mpPoint.x;
            let y = data.code.mpPoint.y;
            let tempData;
            if (pageNum % 2 == 0) {

                tempData = insertPosition[1];
            } else {
                tempData = insertPosition[0];
            }
          
            for (let i in tempData) {
                // 判断鼠标点击的位置是否在外部插入的图标上

                let transformX=parseInt(tempData[i].baseWidth*x/1000);//坐标点转换x
                let transformY=parseInt(tempData[i].baseHeight*y/1000);//坐标点转换Y
                
               for(let j=0;j<tempData[i].arr.length;j++){
                   let item=tempData[i].arr[j];
                   if(transformX >= Number(item['left']) && transformX <= Number(item['width']) + Number(item['left']) && transformY >= Number(item['top']) && transformY <= Number(item['top']) + Number(item['width'])){
                        let playname=item.filename;
                        if (i == 'video') {//视频
                            videoUrl = playname;
                            console.log(playname)
                            $('.audio').attr('src', '');
                            $('#example_video').attr('src', videoUrl);
                            $('.video-play').css({ display: 'block' });
                            return;
                        } else if (i == 'audio') {//音频
                            $('.red-dot').css({ display: 'none' });
                            $('.red-dot').css({ display: 'block' });
                            audioUrl = playname;
                            $('.audio').attr('src', audioUrl);
                            return;
                        } else if (i == 'ppt') {
                            $('.red-dot').css({ display: 'none' });
    
    
                        } else if (i == 'word') {
                            $('.red-dot').css({ display: 'none' });
                        } else if(i==='image') {
                            $('.red-dot').css({ display: 'none' });
                          $('#example_img').attr('src', playname);
                          getImageWidth( $('#example_img').attr('src'),function(w,h){
                              if(w>h){
                                $('#example_img').css('width','100%')
                              }else{
                                $('#example_img').css('height','100%')
                              }
                              
                          })
                            $('.external-img').css({ display: 'flex' });
                            return;
                        }
                        let xhrtp = new XMLHttpRequest();
                        xhrtp.open('POST', DEV_URL + 'playusrfile', true);
                        xhrtp.send(JSON.stringify({ "filename": playname }));
                        return;
                    }
                   
               }
               
            }
            var xhr = new XMLHttpRequest();
            xhr.open('POST', DEV_URL + 'getVAbyXY', true);
            xhr.onload = function (e) {
                var res = JSON.parse(e.srcElement.responseText)
                if (res.data) {
                    $('.red-dot').css({ display: 'block' });
                    if (res.data.languageInfos[0].videos && res.data.languageInfos[0].videos.length > 0) {
                        let videoData = res.data.languageInfos[0].videos;
                        videoData.forEach(item => {
                            if (item.type === 'JCDH') {
                                videoUrl = item.path;
                                $('.audio').attr('src', '')
                                $('#example_video').attr('src', videoUrl);
                                $('.video-play').css({ display: 'block' });
                            }
                        });
                        return;
                    };
                    audioUrl = res.data.languageInfos[0].soundUrls[0];
                    $('.audio').attr('src', audioUrl)
                }
            }
            xhr.send(JSON.stringify(data));
        } else {
            let pageNum = data.code.mpPoint.pageNum;
            let x = data.code.mpPoint.x;
            let y = data.code.mpPoint.y;
            let tempData;
            if (pageNum % 2 == 0) {
                tempData = insertPosition[0];
            } else {
                tempData = insertPosition[1];
            }

            for (let i in tempData) {
                if (x >= tempData[i]['left'] && x <= tempData[i]['width'] + tempData[i]['left'] && y >= tempData[i]['top'] && y <= tempData[i]['top'] + tempData[i]['width']) {
                    if (i == 'video') {//视频
                        videoUrl = tempData[i].filename;
                        $('#example_video').attr('src', videoUrl);
                        $('.video-play').css({ display: 'block' });
                        return;
                    } else if (i == 'audio') {//音频
                        $('.red-dot').css({ display: 'block' });
                        audioUrl = tempData[i].filename;
                        $('.audio').attr('src', audioUrl);
                        return;
                    } else if (i == 'ppt') {
                        return;
                    } else if (i == 'word') {
                        return;
                    } else if (i == 'image') {
                        return;
                    }

                }
            }
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: DEV_URL + "/v1/audios/?insideKey=INTERNAL_VALIDATION_KEY",
                headers: {
                    'Authorization': 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1dWlkIjoiMTllODM5M2M5MmM0NGMtUVQiLCJsb2dpbklkIjoiMTgyMzgxMTY0MDYiLCJqdGkiOiI1NjhhYTEwMTBhMDg0YjEzOGMwZTZhMTdkMWQ1MjkwOCIsImV4cCI6MTY0NzM5NTc1NSwibmJmIjoxNjMxODQzNzU1fQ.4JotA0uepD9TLvAOhUlvLmZlJiCwEfWnUqeYyWOifU8',
                },
                data: JSON.stringify(data),
                success: (res) => {
                    if (res.data) {
                        //显示小红点
                        $('.red-dot').css({ display: 'block' });
                        //判断是否有视频文件
                        if (res.data.languageInfos[0].videos && res.data.languageInfos[0].videos.length > 0) {
                            $('.audio').attr('src', '');
                            let videoData = res.data.languageInfos[0].videos;
                            videoData.forEach(item => {
                                if (item.type === 'JCDH') {
                                    getVideoUrl(item.path);

                                }
                            });
                        };
                        audioUrl = res.data.languageInfos[0].soundUrls[0];
                        $('.audio').attr('src', audioUrl);

                    }
                }
            });

        }
    };

    // 插入外部图片
    async function insert(page) {
        insertPosition = [{}, {}];
        let pageX;
        let pageY;
        let childWidth;
        let childHeight;
        let viewWidth = windowWidth;
        let viewHeight = windowHeight;
        let arr = await imageLoad($('.click-read-all>div').eq(page));
        let filename;//图片src
        childWidth = arr[0];
        childHeight = arr[1];
        pageX = (viewWidth - childWidth * 2) / 2;
        pageY = (viewHeight - childHeight) / 2;

        let data;
        if(!onSize){
            res=[];
        }
        for (let j = 0; j < $('.click-read-all>div').eq(page).children().length; j++) {
            filename = $($('.click-read-all>div').eq(page).children()[j]).attr('src');
            if(!onSize){
                res.push(await getInsertCon(filename));
            }
            if(res[j]){
                data=JSON.parse(res[j]);
                console.log('data',data)
                $('.insert-img>div').eq(page).html('');
                insertPosition[j]['word']={
                    baseWidth:'',
                    baseHeight:'',
                    arr:[]
                };
                insertPosition[j]['ppt']={
                    baseWidth:'',
                    baseHeight:'',
                    arr:[]
                };
                insertPosition[j]['video']={
                    baseWidth:'',
                    baseHeight:'',
                    arr:[]
                };
                insertPosition[j]['audio']={
                    baseWidth:'',
                    baseHeight:'',
                    arr:[]
                };
                insertPosition[j]['image']={
                    baseWidth:'',
                    baseHeight:'',
                    arr:[]
                };
                for (let i = 0; i < data.length; i++) {
                    let left = data[i].Left * childWidth / data[i].baseWidth + pageX + j * childWidth;
                    let top = data[i].Top * childHeight / data[i].baseHeight + pageY;
                    let height = data[i].Height * childHeight / data[i].baseHeight;
                    let width=data[i].Width*childWidth/data[i].baseWidth;
                    if (j == 0) {
                        if (left + height > pageX + childWidth) {
                            left = childWidth + pageX - height;
                        }
                        if (top + height > childHeight + pageY) {
                            top = childHeight + pageY - height;
                        }
                    } else if (j == 1) {
                        if (left + height > viewWidth - pageX) {
                            left = viewWidth - pageX - height;
                        }
                        if (top + height > childHeight + pageY) {
                            top = childHeight + pageY - height;
                        }
                    }
                    if (data[i].icon === 'word.png') {
/*uselocal2pack*/
                        let externalImg = `<img  src='http://mplayer/images/word.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`
                        /*
uselocal2pack/*
                        let externalImg = `<img  src='./images/word.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`
                        /**/
                        $('.insert-img>div').eq(page).append(externalImg);
                      
                        insertPosition[j]['word'].baseWidth=data[i].baseWidth;
                        insertPosition[j]['word'].baseHeight=data[i].baseHeight;
                        insertPosition[j]['word'].arr.push({
                            width: data[i].Width,
                            height: data[i].Height,
                            imgLeft: left,
                            imgTop: top,
                            top: data[i].Top,
                            left:data[i].Left,
                            filename: data[i].filename,
                           
                        })
                       
                    } else if (data[i].icon === 'ppt.png') {
/*uselocal2pack*/
                        let externalImg = `<img src='http://mplayer/images/ppt.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /*
uselocal2pack/*
                        let externalImg = `<img src='./images/ppt.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /**/ 
                        
                        $('.insert-img>div').eq(page).append(externalImg);
                        insertPosition[j]['ppt'].baseWidth=data[i].baseWidth;
                        insertPosition[j]['ppt'].baseHeight=data[i].baseHeight;
                        insertPosition[j]['ppt'].arr.push({
                            width: data[i].Width,
                            height: data[i].Height,
                            imgLeft: left,
                            imgTop: top,
                            top: data[i].Top,
                            left:data[i].Left,
                            filename: data[i].filename,
                           
                        })
                    } else if (data[i].icon === 'image.png') {
/*uselocal2pack*/
                        let externalImg = `<img src='http://mplayer/images/image.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /*
uselocal2pack/*
                        let externalImg = `<img src='./images/image.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /**/ 
                        $('.insert-img>div').eq(page).append(externalImg);
                        insertPosition[j]['image'].baseWidth=data[i].baseWidth;
                        insertPosition[j]['image'].baseHeight=data[i].baseHeight;
                        insertPosition[j]['image'].arr.push({
                            width: data[i].Width,
                            height: data[i].Height,
                            imgLeft: left,
                            imgTop: top,
                            top: data[i].Top,
                            left:data[i].Left,
                            filename: data[i].filename,
                           
                        })
                    } else if (data[i].icon === 'video.png') {
/*uselocal2pack*/
                        let externalImg = `<img src='http://mplayer/images/vedio.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /*
uselocal2pack/*
                        let externalImg = `<img src='./images/vedio.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /**/
                        $('.insert-img>div').eq(page).append(externalImg);
                        insertPosition[j]['video'].baseWidth=data[i].baseWidth;
                        insertPosition[j]['video'].baseHeight=data[i].baseHeight;
                        insertPosition[j]['video'].arr.push({
                            width: data[i].Width,
                            height: data[i].Height,
                            imgLeft: left,
                            imgTop: top,
                            top: data[i].Top,
                            left:data[i].Left,
                            filename: data[i].filename,
                           
                        })
                    } else if(data[i].icon === 'audio.png') {
/*uselocal2pack*/
                        let externalImg = `<img src='http://mplayer/images/audio.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /*
uselocal2pack/*
                        let externalImg = `<img src='./images/audio.png' style='height:${height}px;position:absolute;left:${left}px;top:${top}px'>`;
                        /**/
                        $('.insert-img>div').eq(page).append(externalImg);
                        insertPosition[j]['audio'].baseWidth=data[i].baseWidth;
                        insertPosition[j]['audio'].baseHeight=data[i].baseHeight;
                        insertPosition[j]['audio'].arr.push({
                            width: data[i].Width,
                            height: data[i].Height,
                            imgLeft: left,
                            imgTop: top,
                            top: data[i].Top,
                            left:data[i].Left,
                            filename: data[i].filename,
                           
                        })
                    }
                }  
            } 
        }
    }
   
    //执行切换动画
    function change() {
        $(".click-read-all>div").eq(page).fadeIn(300).siblings().stop(true, true).fadeOut(300);
        $(".insert-img>div").eq(page).fadeIn(300).siblings().stop(true, true).fadeOut(300);
    };
    // 放大缩小
    function changeFactor(factor) {
        $('.main').css('transform', 'scale(' + factor + ')');
        // $('.red-dot').css('transform','scale('+1/factor+')');
        imgH = $('.click-read-all > div').eq(page).children().eq(0).height() * factor;//缩放页面后图片的height
        imgW1 = $('.click-read-all > div').eq(page).children().eq(0).width() * factor;//缩放页面后第一个图片的width
        imgW2 = $('.click-read-all > div').eq(page).children().eq(1).width() * factor;//缩放页面后第二个图片的ewidth
        imgW = imgW1 + imgW2;//图片的总widht
        let left;//main元素图片的左侧留白
        let top;//main元素里面图片的上侧留白
        let mainLeft;//main元素当前的left
        let mainTop;//main top
        mainLeft = Number(Number(($('.main').position().left) / lastZoom * factor).toFixed(1));
        mainTop = Number(Number(($('.main').position().top) / lastZoom * factor).toFixed(1));
        left = -Number(((windowWidth * factor) / 2 - imgW1)).toFixed(1);
        top = -Number((windowHeight * factor - imgH) / 2).toFixed(1);
        if (imgW > windowWidth) {//当前图片的width大于浏览器宽度
            if (left < mainLeft) {//图片左侧的留白小于main元素的left，这个时候图片的left固定为图片的左侧留白
                $('.main').css({ 'left': left + 'px', 'overflow': 'hidden' });

            } else if (Math.abs(mainLeft - windowWidth) + ((windowWidth * factor) / 2 - imgW2) > windowWidth * factor) {
                // main元素width-main元素left-浏览器width>图片右侧留白
                $('.main').css({ 'left': -(windowWidth * factor - ((windowWidth * factor) / 2 - imgW2) - windowWidth) + 'px' });
            } else {//main元素left为本身left
                $('.main').css({ 'left': mainLeft + 'px', 'overflow': 'hidden' });

            }
        } else {//当前图片的width小于浏览器的width，main的left为0
            $('.main').css({ 'left': 0 + 'px', 'overflow': 'hidden' });
        }
        if (imgH > windowHeight) {

            if (top < mainTop) {
                $('.main').css({ 'top': top + 'px', 'overflow': 'hidden' });
            } else if (Math.abs(mainTop - windowHeight) + ((windowHeight * factor - imgH) / 2) > windowHeight * factor) {
                $('.main').css({ 'top': -(windowHeight * factor - (windowHeight * factor - imgH) / 2 - windowHeight) + 'px' });
            } else {
                $('.main').css({ 'top': mainTop + 'px', 'overflow': 'hidden' });
            }
        } else {
            $('.main').css({ 'top': 0 + 'px', 'overflow': 'hidden' });
        }
    };
})
loading();
function loading(){
    
    (function ($) {
        $.fn.loading = function () {
            return this.each(function () {
                var loadingHTNL = `<div class="loading">
            <div class="sk-fading-circle">
                <div class="sk-circle1 sk-circle"></div>
                <div class="sk-circle2 sk-circle"></div>
                <div class="sk-circle3 sk-circle"></div>
                <div class="sk-circle4 sk-circle"></div>
                <div class="sk-circle5 sk-circle"></div>
                <div class="sk-circle6 sk-circle"></div>
                <div class="sk-circle7 sk-circle"></div>
                <div class="sk-circle8 sk-circle"></div>
                <div class="sk-circle9 sk-circle"></div>
                <div class="sk-circle10 sk-circle"></div>
                <div class="sk-circle11 sk-circle"></div>
                <div class="sk-circle12 sk-circle"></div>
            </div>
        </div>`;
                $(this).append(loadingHTNL);
            });
        };
        $.fn.loadingClose = function () {
            return this.each(function () {
                $(this).find('.loading').remove();
            })
        }
    })(jQuery);
}

    